package com.bjb.vr.common.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjb.vr.common.ao.OptCusConfigAo;
import com.bjb.vr.common.ao.SysPlatformAo;
import com.bjb.vr.common.ao.UmsAccountAo;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.dto.*;
import com.bjb.vr.common.mapper.OptCusConfigMapper;
import com.bjb.vr.common.result.BaseResult;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.JwtTokenUtil;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.bjb.vr.common.vo.OptCusConfigVo;
import com.bjb.vr.common.vo.SysPlatformVo;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author admin
 * @description 针对表【opt_cus_config(客户配置信息表)】的数据库操作Service
 * @createDate 2022-06-17 15:01:36
 */
@Service
public class OptCusConfigService extends ServiceImpl<OptCusConfigMapper, OptCusConfig> {

    @Resource
    private UmsAccountService umsAccountService;

    @Autowired
    private OptCusConfigMapper optCusConfigMapper;

    @Resource
    private ResDictionaryService dictionaryService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private SysTenantService tenantService;

    public int DEPLOY_MODE_PRIVATE = 1;
    public int DEPLOY_MODE_CLOUD = 2;
    public int DEPLOY_MODE_MIX = 3;

    public BaseResult addOptCusConfig(OptCusConfigAo optCusConfigAo) {
        Assert.notNull(optCusConfigAo.getTenantId(), "客户租户Id不能为空");

        if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_PRIVATE) {
            Assert.notNull(optCusConfigAo.getPreSerIp(), "私有部署模式前置服务器不能为空");
        } else if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_CLOUD) {
            Assert.notNull(optCusConfigAo.getCloudIp(), "公有云部署模式云服务器不能为空");
        } else if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_MIX) {
            Assert.notNull(optCusConfigAo.getPreSerIp(), "混合部署模式前置服务器不能为空");
            Assert.notNull(optCusConfigAo.getCloudIp(), "混合部署模式云服务器不能为空");
        }
        BaseResult result = new CommonResult<>(false);

        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);

        LambdaQueryWrapper<OptCusConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OptCusConfig::getTenantId, optCusConfigAo.getTenantId());
        OptCusConfig optCusConfigOne = optCusConfigMapper.selectOne(lambdaQueryWrapper);
        if (optCusConfigOne != null) {
            result = CommonResult.Fail("已存在该客户配置信息!");
            return result;
        }
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, false);

        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        umsAccountVo.setTempTenantId(optCusConfigAo.getTenantId());

        OptCusConfig optCusConfig = new OptCusConfig();
        optCusConfig.setThemeCodes(optCusConfigAo.getThemeCodes());
        optCusConfig.setDeployMod(optCusConfigAo.getDeployMod());
        optCusConfig.setPreSerIp(optCusConfigAo.getPreSerIp());
        optCusConfig.setCloudIp(optCusConfigAo.getCloudIp());
        optCusConfig.setVrMonRtmpUrl(optCusConfigAo.getVrMonRtmpUrl());
        this.save(optCusConfig);
        umsAccountVo.setTempTenantId("");
        result = CommonResult.Ok("创建客户配置信息成功!");
        return result;
    }


    public BaseResult updateCusConfig(OptCusConfigAo optCusConfigAo) {
        Assert.notNull(optCusConfigAo.getTenantId(), "客户租户Id不能为空");

        if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_PRIVATE) {
            Assert.notNull(optCusConfigAo.getPreSerIp(), "私有部署模式前置服务器不能为空");
        } else if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_CLOUD) {
            Assert.notNull(optCusConfigAo.getCloudIp(), "公有云部署模式云服务器不能为空");
        } else if (optCusConfigAo.getDeployMod() == DEPLOY_MODE_MIX) {
            Assert.notNull(optCusConfigAo.getPreSerIp(), "混合部署模式前置服务器不能为空");
            Assert.notNull(optCusConfigAo.getCloudIp(), "混合部署模式云服务器不能为空");
        }
        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
        BaseResult result = new CommonResult<>(false);

        UpdateWrapper<OptCusConfig> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("tenant_id",optCusConfigAo.getTenantId());

        OptCusConfig optCusConfig = new OptCusConfig();
        optCusConfig.setId(optCusConfigAo.getId());
        optCusConfig.setThemeCodes(optCusConfigAo.getThemeCodes());
        optCusConfig.setDeployMod(optCusConfigAo.getDeployMod());
        optCusConfig.setPreSerIp(optCusConfigAo.getPreSerIp());
        optCusConfig.setCloudIp(optCusConfigAo.getCloudIp());
        optCusConfig.setVrMonRtmpUrl(optCusConfigAo.getVrMonRtmpUrl());
        optCusConfigMapper.update(optCusConfig,updateWrapper);

        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, false);
        result = CommonResult.Ok("修改客户配置信息成功!");
        return result;
    }


    public OptCusConfigVo queryCusConfigDetail(OptCusConfigAo optCusConfigAo) {
        Assert.notNull(optCusConfigAo.getTenantId(), "租户Id不能为空");

        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);

        MPJLambdaWrapper<OptCusConfigVo> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper
                .select(OptCusConfig::getThemeCodes)
                .select(OptCusConfig::getDeployMod)
                .select(OptCusConfig::getPreSerIp)
                .select(OptCusConfig::getCloudIp)
                .select(OptCusConfig::getVrMonRtmpUrl)
                .select(SysTenant::getTenantName)
                .leftJoin(SysTenant.class, SysTenant::getTenantId, OptCusConfig::getTenantId);
        mpjLambdaWrapper.eq(OptCusConfig::getTenantId, optCusConfigAo.getTenantId());
        OptCusConfigVo optCusConfig = optCusConfigMapper.selectJoinOne(OptCusConfigVo.class, mpjLambdaWrapper);

        ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, false);
        if (optCusConfig != null) {
            buildNeedInfo(optCusConfig);
            return optCusConfig;
        }
        return optCusConfig;
    }

    private void buildNeedInfo(OptCusConfigVo optCusConfigVo) {
        if (optCusConfigVo != null && !StringUtils.isEmpty(optCusConfigVo.getThemeCodes())) {
            String[] themeCodes = optCusConfigVo.getThemeCodes().split(",");
            String themeName = "";
            if (themeCodes.length > 0) {
                for (String themeCode : themeCodes) {
                    ResDictionary resDictionary = dictionaryService.getResDictionaryByCode(themeCode);
                    if (resDictionary != null) {
                        themeName += resDictionary.getDictName() + ",";
                    }
                }
            }
            if (!StringUtils.isEmpty(themeName)) {
                themeName = themeName.substring(0, themeName.length() - 1);
            }
            optCusConfigVo.setThemeNames(themeName);

            //1:私有部署 2:公有云 3:混合云
            if(optCusConfigVo.getDeployMod()==1){
                optCusConfigVo.setDeployModName("私有部署");
            }else if(optCusConfigVo.getDeployMod()==2){
                optCusConfigVo.setDeployModName("公有云");
            }else if(optCusConfigVo.getDeployMod()==3){
                optCusConfigVo.setDeployModName("混合云");
            }
        }

    }

    public SysPlatformVo queryPlatform() {
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        String tenantId = umsAccountVo.getTenantId();
        LambdaQueryWrapper<OptCusConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OptCusConfig::getTenantId, tenantId);
        OptCusConfig cusConfig = this.getOne(queryWrapper);
        // 封装返回对象
        SysPlatformVo platformVo = new SysPlatformVo();
        if (Objects.isNull(cusConfig)) {
            return null;
        }
        BeanUtils.copyProperties(cusConfig, platformVo);
        // 1、设置平台信息
        String[] split = cusConfig.getThemeCodes().split(",");
        String platformName = dictionaryService.getPlatformName(split);
        platformVo.setPlatform(platformName);

        // 2、设置租户信息
        SysTenant sysTenant = tenantService.selectOneSysTenantByTenantId(cusConfig.getTenantId());
        platformVo.setTenantName(sysTenant.getTenantName());
        platformVo.setUsername(umsAccountVo.getUsername());
        return platformVo;
    }

    /**
     * 选择当前租户的平台版本
     *
     * @param sysPlatformAo
     * @return
     */
    public boolean choicePlatform(SysPlatformAo sysPlatformAo) {
        String platformValue = sysPlatformAo.getPlatform();
        UmsAccountVo umsAccountVo = (UmsAccountVo) ThreadLocalUtil.get(ThreadLocalConstant.USER_ACCOUNT_INFO);
        UmsAccount umsAccount = umsAccountService.getById(umsAccountVo.getId());
        umsAccount.setPlatform(platformValue);
        // 封装对象
        SysPlatform sysPlatform = new SysPlatform();
        BeanUtils.copyProperties(umsAccountVo, sysPlatform);
        sysPlatform.setAccountId(umsAccountVo.getUserId());
        sysPlatform.setPlatform(platformValue);
        ResDictionary dictionary = dictionaryService.getDictionaryByName(platformValue);
        sysPlatform.setPlatformCode(dictionary.getDictCode());
        String refreshTokenId = SecureUtil.md5(umsAccountVo.getUsername()).toUpperCase();

        try {
            // 更新Redis缓存
            redisUtil.hset(TokenConstants.PLATFORM_TOKEN_KEY + refreshTokenId, TokenConstants.PLATFORM_MAP_KEY, sysPlatform);
            redisUtil.expire(TokenConstants.PLATFORM_TOKEN_KEY + refreshTokenId, TokenConstants.EXPIRATION, TimeUnit.MINUTES);

            // 更新数据库
            umsAccountService.updateById(umsAccount);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 查询用户选择的平台信息
     *
     * @param umsAccountAo
     */
    public void queryChoicedPlatform(UmsAccountAo umsAccountAo) {
        Claims claims = JwtTokenUtil.parseJWT(umsAccountAo.getAuthorization());
        String username = String.valueOf(claims.get(TokenConstants.TOKEN_USERNAME));
        // 查询缓存
        String refreshTokenId = SecureUtil.md5(username).toUpperCase();
        SysPlatform sysPlatform = (SysPlatform) redisUtil.hget(TokenConstants.PLATFORM_TOKEN_KEY + refreshTokenId, TokenConstants.PLATFORM_MAP_KEY);
        if (Objects.isNull(sysPlatform)) {
            sysPlatform = new SysPlatform();
            UmsAccountVo accountInfo = umsAccountService.getAccountInfo(umsAccountAo);
            BeanUtils.copyProperties(accountInfo, sysPlatform);
            sysPlatform.setAccountId(accountInfo.getUserId());
            sysPlatform.setPlatform(accountInfo.getPlatform());
            if (!StringUtils.isEmpty(accountInfo.getPlatform())) {
                ResDictionary dictionary = dictionaryService.getDictionaryByName(accountInfo.getPlatform());
                sysPlatform.setPlatformCode(dictionary.getDictCode());
            }
        }
        ThreadLocalUtil.set(ThreadLocalConstant.USER_PLATFORM_INFO, sysPlatform);
    }
}
